package peer;

import peer.Config;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import net.miginfocom.swing.MigLayout;
import peer.rdp.Route;
import peer.swtdesigner.SwingResourceManager;
import peer.tools.currentTimeAndCpuInfo;

import com.lamatek.util.JFileFilter;


public class Ui implements WindowListener{
	JFrame mainFrame;
	JList shareList;
	DefaultListModel listModel;
	JTextArea addressta;
	JTextArea statusta;
	static String url=null;
	static boolean playUrl=false;
	static boolean min=false;
	Thread statusMonitThread;
	static String stateStr="";
	TrayIcon trayIcon;
	Image ui ;
	Image ui2;
	SystemTray tray;
	boolean cbSelected=false;
	boolean lockPub=false;
	static boolean openfolder=false;
	//testsvn
	public static void main(String args[]){
		for(int i=0;i<args.length;i++){
			if(args[i].equals("-openfolder")){
				openfolder=true;
			}
		}
		new Ui(openfolder);
	}
	
	@SuppressWarnings({ "deprecation", "unchecked" })
	public Ui(boolean min) {
		new Config();
		//peer.Config.setAutoRun(peer.Config.getAutoRun());
		if(peer.Config.singleThread){
			try {
				final DatagramSocket ds=new DatagramSocket(peer.Config.uiPort);
				new Thread(){
					public void run(){
						byte[] data=new byte[1024];
						DatagramPacket dp=new DatagramPacket(data,data.length);
						while(true){
							try {
								ds.receive(dp);
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}.start();
			} catch (SocketException e1) {
				if(playUrl){          
					if(!url.startsWith("lightvod2://start")){
						peer.Config.playUrl(url);
					}
				}
				//e1.printStackTrace();
				System.exit(0);
			}
		}
		
		mainFrame=new JFrame("发布管理器");
	//	mainFrame.setMinimumSize(new Dimension(400,420));
		/*
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (ClassNotFoundException e2) {
			e2.printStackTrace();
		} catch (InstantiationException e2) {
			e2.printStackTrace();
		} catch (IllegalAccessException e2) {
			e2.printStackTrace();
		} catch (UnsupportedLookAndFeelException e2) {
			e2.printStackTrace();
		}
		SwingUtilities.updateComponentTreeUI(mainFrame);
		*/
		mainFrame.setIconImage(SwingResourceManager.getImage(peer.Config.basePath+"skin/ui.gif"));
		MigLayout layout=new MigLayout("","[left][left]","[top][top][top]");
		mainFrame.setLayout(layout);
		mainFrame.addWindowListener(this);
		mainFrame.setBounds(peer.Config.getMainFrameBound());
		
		listModel=new DefaultListModel();
		shareList=new JList(listModel);
		shareList.setName("list");
		shareList.addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent e) {
				JList list = (JList) e.getSource();
		        int selections[] = list.getSelectedIndices();
		        Object selectedValues[] = list.getSelectedValues();
		        for (int i = 0, n = selections.length; i < n; i++) {
			      	String fileStr=(String) selectedValues[i];
					if(Config.shareFileStrMange.containsShareFile(new File(fileStr))){
						addressta.setText(getPubUrl(fileStr,true));
					}
		        }
			}
		});
		
		JPanel listPanel = new JPanel();
		listPanel.setLayout(new BorderLayout());
		listPanel.add(shareList,BorderLayout.SOUTH);
		listPanel.add(new JScrollPane(shareList), BorderLayout.CENTER);
		
		mainFrame.getContentPane().add(listPanel,"cell 0 0,height 0:2048:2048,width 0:2048:2048,growx,growy,wrap");
		
		addressta = new JTextArea();
		if(!peer.Config.hideUi){
			mainFrame.setVisible(true);
		}

		addressta.setBackground(mainFrame.getContentPane().getBackground());
		statusta = new JTextArea();
		statusta.setBackground(mainFrame.getContentPane().getBackground());
		final JPanel panel = new JPanel();
		MigLayout mig5 = new MigLayout("","[][][][][]","[]");
		panel.setLayout(mig5);
		mainFrame.getContentPane().add(panel,"cell 1 0,height ::1024,width :80:125");

		JButton repub=new JButton("重新发布");
		panel.add(repub,"wrap,growx");
		repub.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Thread (){
					public void run(){
						System.out.println("aaaaaaaaa");
						peer.Config.shareFileMange.pubAllFile();
						peer.Config.cacheFileMange.pubAllCache();
					}
				}.start();
			}
		});
		JButton money=new JButton("设置广告地址");
		panel.add(money,"wrap,growx");
		money.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String adv =JOptionPane.showInputDialog("",peer.Config.getAdv2());
				if(adv!=null){
					if(adv.startsWith("http://")|adv.startsWith("")){
						System.out.println(adv);
						peer.Config.setAdv2(adv);
					}else{
						if(!adv.equals("")){
							JOptionPane.showMessageDialog(null, "地址格式错误，请以http://开头");
						}
						
					}
				}
			}
		});
		
//		JButton export=new JButton("导出地址列表");
//		panel.add(export,"wrap,growx");
//		export.addActionListener(
//				new ActionListener() {
//				public void actionPerformed(ActionEvent e) {
//					JFileChooser fileChooser = new JFileChooser(peer.Config.getLastOpenDirConsole());
//					JFileFilter fl=new JFileFilter();
//					fl.addExtension("txt");
//					fl.setDescription("文本文件");
//					fileChooser.setFileFilter(fl);
//					fileChooser.setDialogTitle("选择导出文件...");
//					int status = fileChooser.showSaveDialog(mainFrame);
//					if (status == JFileChooser.APPROVE_OPTION) {
//						File selectedFile = fileChooser.getSelectedFile();
//						String filePath=selectedFile.getAbsolutePath();
//						int index=filePath.lastIndexOf(".");
//						String extendName="";
//						if(index>0){
//							extendName=filePath.substring(index+1);
//							System.out.println("WWWWWWWW "+extendName);
//						}
//						if(!extendName.equalsIgnoreCase("txt")){
//							filePath+=".txt";
//							selectedFile=new File(filePath);
//						}
//						peer.Config.setLastOpenDirConsole(selectedFile.getParent());
//						exportShareList(selectedFile);
//					}
//				}
//				}
//				);
		JButton export=new JButton("更新播放列表");
		panel.add(export,"wrap,growx");
		export.addActionListener(
				new ActionListener() {
				public void actionPerformed(ActionEvent e) {
//					JFileChooser fileChooser = new JFileChooser(peer.Config.getLastOpenDirConsole());
//					JFileFilter fl=new JFileFilter();
//					fl.addExtension("txt");
//					fl.setDescription("文本文件");
//					fileChooser.setFileFilter(fl);
//					fileChooser.setDialogTitle("选择导出文件...");
//					int status = fileChooser.showSaveDialog(mainFrame);
//					if (status == JFileChooser.APPROVE_OPTION) {
//						File selectedFile = fileChooser.getSelectedFile();
//						String filePath=selectedFile.getAbsolutePath();
//						int index=filePath.lastIndexOf(".");
//						String extendName="";
//						if(index>0){
//							extendName=filePath.substring(index+1);
//							System.out.println("WWWWWWWW "+extendName);
//						}
//						if(!extendName.equalsIgnoreCase("txt")){
//							filePath+=".txt";
//							selectedFile=new File(filePath);
//						}
//						peer.Config.setLastOpenDirConsole(selectedFile.getParent());
//						exportShareList(selectedFile);
//					}
					String savePath = "C:\\Inetpub\\wwwroot\\PlayList\\";
					
					String infoXML = savePath +  "info.xml";
					File playerListFolder =new File(savePath);
					
					//如果目录不存在创建目录
					if(!playerListFolder.exists()){
						playerListFolder.mkdirs();
					}
					//File saveFile = new File(PlayListData);
					//exportPlayListXML(saveFile);
					exportInfoXML(infoXML);
					System.out.println("Success:" + infoXML);
				}
				}
				);

		
		JButton copy=new JButton("复制资源地址");
	//	panel.add(copy,"wrap,growx");
		copy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index=shareList.getSelectedIndex();
				Clipboard clip= Toolkit.getDefaultToolkit().getSystemClipboard(); 
				int index2=shareList.getSelectedIndex();
					if(index2>=0){
						String fileStr=(String) listModel.get(index);
						Transferable tText = new StringSelection(getPubUrl(fileStr,true)); 
						clip.setContents(tText, null); 
				}
			}
		});
		
		
		JButton copy3=new JButton("复制http地址");
		//panel.add(copy3,"wrap,growx");
		copy3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index=shareList.getSelectedIndex();
				Clipboard clip= Toolkit.getDefaultToolkit().getSystemClipboard(); 
				int index2=shareList.getSelectedIndex();
					if(index2>=0){
						String fileStr=(String) listModel.get(index);
						Transferable tText = new StringSelection(getPubUrl(fileStr,false)); 
						clip.setContents(tText, null); 
				}
			}
		});

		final JButton button = new JButton();
		button.setText("播放");
		//panel.add(button,"wrap,growx");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index=shareList.getSelectedIndex();
				int index2=shareList.getSelectedIndex();
				if(index2>=0){
					String fileStr=(String) listModel.get(index);
					//String address=getPubUrl(fileStr,true);
					peer.Config.playUrl(fileStr);
				}
			}
		});
		
		final JButton open = new JButton();
		open.setText("打开");
		//panel.add(open,"wrap,growx");
		open.addActionListener(
			new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index=shareList.getSelectedIndex();
				int index2=shareList.getSelectedIndex();
				if(index2>=0){
					String fileStr=(String) listModel.get(index);
					String address=getPubUrl(fileStr,false);
					peer.Config.openUrl(address);
				}
			
			}
		});
		
		JButton add=new JButton("添加");
		panel.add(add,"wrap,growx");
		add.setName("add");
		add.addActionListener(
		new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			if(!lockPub){
				JFileChooser fileChooser = new JFileChooser(peer.Config.getLastOpenDirConsole());
				fileChooser.setDialogTitle("选择要发布的文件或目录...");
				fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
				JFileFilter fl=new JFileFilter();
				fl.addExtension("rmvb");
				fl.addExtension("rm");
				fl.addExtension("wmv");
				fl.addExtension("avi");
				fl.addExtension("flv");
				fl.addExtension("mp3");
				fl.addExtension("wma");
				fl.setDescription("音视频文件");
			//	fileChooser.setFileFilter(fl);

				int status = fileChooser.showOpenDialog(null);
				if (status == JFileChooser.APPROVE_OPTION) {
					final File selectedFile = fileChooser.getSelectedFile();
					peer.Config.setLastOpenDirConsole(selectedFile.getParent());
					new Thread(){
						public void run(){
							lockPub=true;
							if(selectedFile.isFile()){
								statusta.setText("正在添加文件"+selectedFile.getAbsolutePath());
								tryAddPubFile(selectedFile);
							}else{
								final ArrayList<File> fileList=new ArrayList<File>();
								getFileList(selectedFile,fileList);
								for(int i=0;i<fileList.size();){
									statusta.setText("正在添加文件"+"("+(i+1)+"/"+fileList.size()+") "+fileList.get(i).getAbsolutePath());
									tryAddPubFile(fileList.get(i));
									statusta.setText("");
									i++;
								}
							
							}
							lockPub=false;
						}
					}.start();
					
					
				}
			}
			
		}
		}
		);
		
		mainFrame.getContentPane().add(addressta,"cell 0 1,span 2");
		mainFrame.getContentPane().add(statusta,"cell 0 2,span 2,align right");
		
		JButton remove=new JButton("删除");
		panel.add(remove,"wrap,growx");
		remove.setName("remove");
		remove.addActionListener(
		new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(!lockPub){
					int index=shareList.getSelectedIndex();
					if(index>=0){
						String fileStr=(String) listModel.get(index);
						listModel.remove(index);
						Config.shareFileStrMange.removeShareFile(fileStr);
					}
				}
				
		}
	});
		

		final JButton about = new JButton();
		//panel.add(about,"wrap,growx");
		about.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				peer.Config.openUrl("http://www.baidu.com");
			}
		});
		about.setText("帮助");

		final JButton help = new JButton();
		//panel.add(help,"wrap,growx");
		help.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				peer.Config.openUrl("http://www.baidu.com/");
			}
		});
		help.setText("关于");
		

		JButton quit = new JButton();
		panel.add(quit,"wrap,growx");
		quit.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent arg0) {
				synchronized(this){
					exit();
				}
			}
		});
		quit.setText("退出");
		
		final JCheckBox cb=new JCheckBox("自动运行",peer.Config.getAutoRun());
		panel.add(cb,"wrap,growx");
		cbSelected=cb.isSelected();
		cb.addChangeListener(new ChangeListener(){
			public void stateChanged(ChangeEvent arg0) {
				if(cbSelected!=cb.isSelected()){
					cbSelected=cb.isSelected();
					peer.Config.setAutoRun(cbSelected);
				}
			}
		});
		
		Config.iniLocal();
		listModel.clear();
		if(!Config.hideUi){
			iniSysTray();
		}
		
		HashMap<String, String> ht=Config.shareFileStrMange.getHm();
		Iterator<String> it=ht.keySet().iterator();
		
		ArrayList<String> list=new ArrayList<String>();
		while (it.hasNext()){
			String filePath=it.next();
			list.add(filePath);
		}
		Object[] list2=list.toArray();
		Comparator cmp = Collator.getInstance(java.util.Locale.CHINA);
        Arrays.sort(list2, cmp);
        
		for(int i=0;i<list2.length;i++){
			listModel.addElement(list2[i]);
		}
		statusMonitThread=new Thread(){
			public void run(){
				while(true){
					if(Config.isLive){
						trayIcon.setImage(ui);
					}else{
						trayIcon.setImage(ui2);
					}
					if(!lockPub){
						statusta.setText(getStatString(false));
					}
					
					trayIcon.setToolTip(getStatString(true));
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		if(!Config.hideUi){
			statusMonitThread.start();
		}
		
		new Thread(){
			public void run(){
				for(int i=0;i<10;i++){
					if(listModel.size()>0){
						listModel.set(0, listModel.get(0));
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					};
				}
				
			}
		}.start();
		if(playUrl){
			if(!url.startsWith("lightvod2://start")){
				peer.Config.playUrl(url);
			}
		}
		Config.runUpdate();
		Config.iniNet();
	}
	
	
	@SuppressWarnings("deprecation")
	
	public static String getStatString(boolean tray){
		String state="";
		String advs="";
		String s=Config.getAdv();
		if(!tray){
			advs+="广告地址";
			if(s.startsWith("http://")){
				advs+=s;
			}else{
				advs+="未设置";
			}
			
		}
		String s2="";
		if(Config.isLive){
			s2="在线";
		}else{
			s2="离线";
		}
		//+"  监听地址"+peer.Config.outIp+":"+peer.Config.RoutePort
		state=advs+"  "+ s2+"  "+"连接数"+Route.connectSum+"  上传"+Route.upSpeed2+"K"+"  下载"+Route.downSpeed2+"K";
		return state;
	}
	
	public void windowOpened(WindowEvent arg0) {
		
	}
	public void windowClosing(WindowEvent arg0) {
		mainFrame.setVisible(false);
	}
	public void windowClosed(WindowEvent arg0) {
		
	}
	public void windowIconified(WindowEvent arg0) {
		
	}
	public void windowDeiconified(WindowEvent arg0) {
		
	}
	public void windowActivated(WindowEvent arg0) {
		
	}
	public void windowDeactivated(WindowEvent arg0) {
		
	}
	
	void iniSysTray(){
		tray = SystemTray.getSystemTray();
		ui = Toolkit.getDefaultToolkit().getImage(peer.Config.basePath+"skin/ui.gif");
		ui2 = Toolkit.getDefaultToolkit().getImage(peer.Config.basePath+"skin/ui2.gif");
		ActionListener listener = new ActionListener() {
		    @SuppressWarnings("deprecation")
		    public void actionPerformed(ActionEvent e) {
		    	mainFrame.setVisible(true);
		    }
		};
		PopupMenu popup = new PopupMenu();
		MenuItem item1 = new MenuItem("关于");
		item1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				peer.Config.openUrl("http://www.lightvod.com");
			}
		});
		MenuItem item2 = new MenuItem("更新");
		item2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				peer.Config.runUpdate2();
			}
		});
		MenuItem item3 = new MenuItem("EXIT Application");
		ActionListener al=new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				String command=e.getActionCommand();
				if(command.equals("EXIT Application")){
					exit();
				}
			}
		};
		item3.addActionListener(al);
//	    popup.add(item1);
//	    popup.add(item2);
	    popup.add(item3);
	   trayIcon = new TrayIcon(ui2, "System Tray ",popup);
	    trayIcon.setImageAutoSize(true);
	    if(peer.Config.uiVisual){
		  	trayIcon.addActionListener(listener);
		}
	  	try {
	  		tray.add(trayIcon);
	  	} catch (AWTException e1) {                        
	  		e1.printStackTrace();
	  	} 
	}
	
	public void minimizeToTray(){
		
	}
	
	String getPubUrl(String  fileStr ,boolean light){
      	File file=new File(fileStr);
		String mds=Config.shareFileStrMange.getShareFile(fileStr);
		String text="";
		if(Config.shareFileStrMange.containsShareFile(new File(fileStr))){
//			if(light){
//				text+="lightvod://";
//			}
			text+="http://127.0.0.1:"+peer.Config.localHttpPort+"/"+mds+"."+file.length()+"."+file.getName();
		}
		return text;
	}
//	
//	String getPubUrl(String  fileStr ,boolean light){
//      	File file=new File(fileStr);
//		String mds=Config.shareFileStrMange.getShareFile(fileStr);
//		String text="";
//		if(Config.shareFileStrMange.containsShareFile(new File(fileStr))){
//			if(light){
//				text+="[lv="+"lightvod://";
//			}
//			text+="http://127.0.0.1:"+peer.Config.localHttpPort+"/"+mds+"."+file.length()+"."+file.getName()+"]"+file.getName()+"[/lv]";
//		}
//		return text;
//	}
	
	void exit(){
		peer.Config.setMainFrameBound(mainFrame.getBounds());
		System.exit(0);
	}
	

	//获得真实文件名
	//zsb
	

	String getPublicUrl(String  fileStr ,boolean light){
      	File file=new File(fileStr);
		String mds=Config.shareFileStrMange.getShareFile(fileStr);
		String text="";
		if(Config.shareFileStrMange.containsShareFile(new File(fileStr))){
//			if(light){
//				text+="P2PstreamPlayer2://";
//			}
			text+="http://61.155.169.23:"+peer.Config.localHttpPort+"/"+mds+"."+file.length()+"."+file.getName();
		}
		return text;
	}
	String getTrueFileName(String filestr)
	{
		File file = new File(filestr);
		String text = "";
		if(Config.shareFileStrMange.containsShareFile(new File(filestr)))
		{
			text += file.getName();
		}
		return text;
	}
	//输出共享文件名
	//zsb
	void exportFileNname(File file){
		try {
			FileWriter fw=new FileWriter(file);

			PrintWriter pw=new PrintWriter(fw);
			//String head  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			//pw.write(head);
			//pw.write("\r\n");
			for(int i=0;i<listModel.getSize();i++){
				String address=(String) listModel.get(i);
				String trueName=getTrueFileName(address);
				int index = trueName.lastIndexOf(".");
				trueName = trueName.substring(0,index);
				trueName += "\r\n";
				pw.write(trueName);
			}
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	void exportInfoXML(String file)
	{
try{
			
			FileWriter fw=new FileWriter(file);
			PrintWriter pw=new PrintWriter(fw);
			String head  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			pw.write(head);
			pw.write("\n\r");
			//pw.write("<Root>");
			pw.write("<List>\n\r");
			for(int i=0;i<listModel.getSize();i++)
			{
				//pw.write("<Movie>\n\r");
				pw.write("<Movie ID=\"" + String.valueOf(i) + "\">\n\t");
				String address=(String) listModel.get(i);
				
				
				//输入所在文件夹名称
				String floderName;
				int pointIndex = address.lastIndexOf("\\");
				floderName = address.substring(0, pointIndex);
				pointIndex = floderName.lastIndexOf("\\");
				String fn = floderName.substring(pointIndex+1,floderName.length());
				pw.write("<FloderName>");
				pw.write(fn);
				pw.write("</FloderName>\n\r");
				
				//输出电影所在的物理地址
				pw.write("<PhysicalAddress>");
				pw.write(address);
				pw.write("</PhysicalAddress>\n\r");
				String trueName=getTrueFileName(address);
				int index = trueName.lastIndexOf(".");
				trueName = trueName.substring(0,index);
				//trueName += "\r\n\r";
				//输出电影文件名
				pw.write("<MovieName>");
				pw.write(trueName);
				pw.write("</MovieName>\n\r");
				
				//String address=(String) listModel.get(i);
				String url=getPubUrl(address,true);
				//输出转化为流后的地址(供P2P使用)
				pw.write("<StreamAddress>");
				pw.write(url);
				pw.write("</StreamAddress>\n\r");
				
				//输入公网IP流地址 (非P2使用)
				String PublicUrl = getPublicUrl(address,true);
				pw.write("<PublicIpAddress>");
				pw.write(PublicUrl);
				pw.write("</PublicIpAddress>\n\r");
				
				//if(i!=listModel.getSize()-1){
				//	pw.write("\n\r");
				//输出描述信息
				pw.write("<Description>");
				pw.write("暂时没有对此片的描述");
				pw.write("</Description>\n\r");
				pw.write("<Reserve1>");
				pw.write("保留项");
				pw.write("</Reserve1>\n\r");
				pw.write("<Reserve2>");
				pw.write("保留项");
				pw.write("</Reserve2>\n\r");
				pw.write("<Reserve3>");
				pw.write("保留项");
				pw.write("</Reserve3>\n\r");
				pw.write("</Movie>\n\r");
			}
			pw.write("</List>");
			//pw.write("</Root>");
				fw.close();

		}catch (IOException e)
		{
			e.printStackTrace();
		}
       
	}
	//zsb
	//以XML格式输出播放列表 
	void exportPlayListXML(File file)
	{
		
		try{
			
			FileWriter fw=new FileWriter(file);
			PrintWriter pw=new PrintWriter(fw);
			String head  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			pw.write(head);
			pw.write("\n\r");
			//pw.write("<Root>");
			pw.write("<List>\n\r");
			for(int i=0;i<listModel.getSize();i++)
			{
				//pw.write("<Movie>\n\r");
				pw.write("<Movie ID=\"" + String.valueOf(i) + "\">\n\t");
				String address=(String) listModel.get(i);
				String trueName=getTrueFileName(address);
				int index = trueName.lastIndexOf(".");
				trueName = trueName.substring(0,index);
				//trueName += "\r\n\r";
				pw.write("<Name>");
				pw.write(trueName);
				pw.write("</Name>\n\r");
				
				//String address=(String) listModel.get(i);
				String url=getPubUrl(address,true);
				pw.write("<URL>");
				pw.write(url);
				pw.write("</URL>\n\r");
				//if(i!=listModel.getSize()-1){
				//	pw.write("\n\r");
				pw.write("<Description>");
				pw.write("暂时没有对此片的描述");
				pw.write("</Description>\n\r");
				pw.write("<Reserve>");
				pw.write("</Reserve>\n\r");
				pw.write("</Movie>\n\r");
			}
			pw.write("</List>");
			//pw.write("</Root>");
				fw.close();

		}catch (IOException e)
		{
			e.printStackTrace();
		}
       
	}
	void exportPlayListXML(String filePath){
        FileOutputStream stream;// provides file access   
        OutputStreamWriter pw;// writes to the file   
           
            try {
					stream = new FileOutputStream(filePath);
					pw = new OutputStreamWriter(stream,"UTF-8");
					
						String head  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
						pw.write(head);
						pw.write("\n\r");
						//pw.write("<Root>");
						pw.write("<List>\n\r");
						for(int i=0;i<listModel.getSize();i++)
						{
							//pw.write("<Movie>\n\r");
							pw.write("<Movie ID=\"" + String.valueOf(i) + "\">\n\t");
							String address=(String) listModel.get(i);
							String trueName=getTrueFileName(address);
							int index = trueName.lastIndexOf(".");
							trueName = trueName.substring(0,index);
							//trueName += "\r\n\r";
							pw.write("<Name>");
							pw.write(trueName);
							pw.write("</Name>\n\r");
							
							//String address=(String) listModel.get(i);
							String url=getPubUrl(address,true);
							pw.write("<URL>");
							pw.write(url);
							pw.write("</URL>\n\r");
							//if(i!=listModel.getSize()-1){
							//	pw.write("\n\r");
							pw.write("<Description>");
							pw.write("暂时没有对此片的描述");
							pw.write("</Description>\n\r");
							pw.write("<Reserve>");
							pw.write("</Reserve>\n\r");
							pw.write("</Movie>\n\r");
						}
						pw.write("</List>");
						pw.flush();
						//pw.write("</Root>");
						pw.close();
						stream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
		 
		
	}
	
	void exportShareList(File file){
		try {
			FileWriter fw=new FileWriter(file);
			PrintWriter pw=new PrintWriter(fw);
			for(int i=0;i<listModel.getSize();i++){
				String address=(String) listModel.get(i);
				String url=getPubUrl(address,true);
				pw.write(url);
				if(i!=listModel.getSize()-1){
					pw.write("\n");
				}
			}
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	void tryAddPubFile(final File file){
		if(!Config.shareFileStrMange.containsShareFile(file)){
			try {
				System.out.println("RRRRRRRRRR "+file.getAbsolutePath());
				Config.shareFileStrMange.addShareFile(file);
				listModel.addElement(file.getAbsolutePath());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			statusta.setText("");
		
		}
	}
	
	public boolean acceptFileType(File f) {
  	  int index=f.getName().lastIndexOf(".");
  	  boolean b=false;
  	  String extendName="";
  	  if(index>0){
  		  extendName= f.getName().substring(index+1);
  		  if(
  				  extendName.equalsIgnoreCase("wmv")|extendName.equalsIgnoreCase("")
  				  |extendName.equalsIgnoreCase("rm")
  				  |extendName.equalsIgnoreCase("rmvb")
  				  |extendName.equalsIgnoreCase("flv")
  				  |extendName.equalsIgnoreCase("wma")
  				  |extendName.equalsIgnoreCase("mp3")
  				  |extendName.equalsIgnoreCase("avi")
  				  ){
  			  b=true;
  		  }
  	  }
      if(b||f.isDirectory()){
        return true;
      }
      return false;
    }
	
	public ArrayList<File> getFileList(File f,ArrayList<File> fileList){
        try {   
        	File[] fs=f.listFiles();   
        	for(int i=0;i<fs.length;i++){   
        		if(fs[i].isFile()){   
        			if(acceptFileType(fs[i])){
        				fileList.add(fs[i]);
        			}
        		}else{
        			getFileList(fs[i],fileList);
        		}   
        	}   
        }catch(Exception e){   
        	
        }   
        return fileList;
	}
}
